<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="所在区域：" prop="region">
          <el-select
            v-model="queryParams.region"
            placeholder="所在区域"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="item in regionList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="关注程度：" prop="attentionLevel">
          <el-select
            v-model="queryParams.attentionLevel"
            placeholder="关注程度"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="item in attentionLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="企业名称：" prop="pollutename">
          <el-input
            style="width: 150px"
            v-model="queryParams.pollutename"
            placeholder="企业名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备名称：" prop="devicename">
          <el-input
            style="width: 150px"
            v-model="queryParams.devicename"
            placeholder="设备名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备MN：" prop="datagathercode">
          <el-input
            style="width: 150px"
            v-model="queryParams.datagathercode"
            placeholder="设备MN"
          ></el-input>
        </el-form-item>
        <div class="searchBtnBox">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            style="padding: 10px"
            >查询</el-button
          >
          <el-button @click="resetQuery" style="padding: 10px">
            <i class="iconfont icon-saoba"></i>
            重置
          </el-button>
        </div>
      </el-form>
    </el-card>
    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:device:add']"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="tableList.rows"
        stripe
        :height="tableHeight"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="datagathercode" label="设备MN" />
        <el-table-column prop="devicename" label="设备名称" />
        <el-table-column prop="county" label="行政区划" />
        <el-table-column prop="pollutename" label="企业名称" />
        <el-table-column prop="outportname" label="排放口名称" />
        <el-table-column prop="longitude" label="经度" />
        <el-table-column prop="latitude" label="纬度" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="view(scope.row)">查看</el-button>
            <el-button type="text" @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>
    <!-- 添加设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="title === '查看设备'"
        label-width="150px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备MN" prop="datagathercode">
              <el-input
                v-model="form.datagathercode"
                placeholder="请输入设备MN"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="devicename">
              <el-input
                v-model="form.devicename"
                placeholder="请输入设备名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备通讯传输方式" prop="deviceTransmission">
              <el-input
                v-model="form.deviceTransmission"
                placeholder="请输入设备通讯传输方式"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="数据包通讯传输方式"
              prop="dataPacketTransmission"
            >
              <el-input
                v-model="form.dataPacketTransmission"
                placeholder="请输入数据包通讯传输方式"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称" prop="pollutename">
              <el-select
                v-model="form.pollutename"
                placeholder="请选择企业名称"
                style="width: 100%"
                clearable
                @change="qyChange"
              >
                <el-option
                  v-for="item in enterpriseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排口名称" prop="outportcode">
              <el-select
                v-model="form.outportcode"
                placeholder="请选择排口名称"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in outletOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select
                v-model="form.deviceStatus"
                placeholder="请选择设备状态"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in deviceStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仪器型号" prop="instrumentModel">
              <el-input
                v-model="form.instrumentModel"
                placeholder="请输入仪器型号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title !== '查看设备'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {
//   getDeviceList,
//   deleteDevice,
//   addDevice,
//   editDevice,
//   exportDevice,
//   getEnterpriseList,
//   getOutletList,
// } from "@/api/device.js";
import { getRegionList } from "@/api/dataResources/monitorData/region.js";
import {
  getSbTableList,
  delSb,
  addSb,
  updateSb,
  getSbDetail,
  getQyList,
  getPkList,
} from "@/api/zhManagement.js";
export default {
  name: "DeviceManagement",
  data() {
    return {
      tableHeight: window.innerHeight - 480,
      regionList: [], //行政区划的下拉列表
      enterpriseOptions: [], //企业污染源的下拉列表
      outletOptions: [], // 排口的下拉列表
      deviceStatusOptions: [
        { label: "运行中", value: "运行中" },
        { label: "故障", value: "故障" },
        { label: "维护中", value: "维护中" },
      ],
      attentionLevelOptions: [
        { label: "全部", value: "全部" },
        { label: "重点关注", value: "重点关注" },
        { label: "一般关注", value: "一般关注" },
      ],
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        region: "",
        // attentionLevel: "全部",
        pollutename: "",
        devicename: "",
        datagathercode: "",
      },
      tableList: {
        total: 0,
        rows: [],
      },
      // 选中数组
      ids: [],
      // 是否显示新增/修改弹出层
      open: false,
      // 弹出层标题
      title: "添加设备",
      // 表单参数
      form: {
        datagathercode: "",
        devicename: "",
        deviceTransmission: "",
        dataPacketTransmission: "",
        longitude: "",
        latitude: "",
        pollutename: "",
        outportcode: "",
        deviceStatus: "",
        instrumentModel: "",
      },
      // 表单校验
      rules: {
        datagathercode: [
          { required: true, message: "设备MN不能为空", trigger: "blur" },
        ],
        devicename: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "blur" },
        ],
        pollutename: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
        ],
        outportcode: [
          { required: true, message: "排口名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getRegionList();
    this.getQyList();
  },
  mounted() {
    // 监听窗口大小变化，动态调整表格高度
    window.addEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 480;
    });
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 480;
    });
  },
  methods: {
    async getRegionList() {
      let res = await getRegionList();
      if (res.code == 200) {
        this.regionList = res.rows;
      }
    },
    // 获取企业下拉列表
    getQyList() {
      getQyList().then((res) => {
        if (res.code === 200) {
          this.enterpriseOptions = res.data.map((item) => ({
            label: item.pollutename,
            value: item.polluteid,
          }));
        }
      });
    },
    // 根据企业污染源获取排口
    getPkList(id) {
      getPkList(id).then((res) => {
        if (res.code === 200) {
          this.outletOptions = res.data.map((item) => ({
            label: item.outportname,
            value: item.outportcode,
          }));
        }
      });
    },

    // 企业污染源改变
    qyChange(value) {
      this.form.outportcode = "";
      if (value) {
        this.getPkList(value);
      } else {
        this.outletOptions = [];
      }
    },

    // 表格checkbox选择数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {
        datagathercode: "",
        devicename: "",
        deviceTransmission: "",
        dataPacketTransmission: "",
        longitude: "",
        latitude: "",
        pollutename: "",
        outletName: "",
        deviceStatus: "",
        instrumentModel: "",
      };
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = { ...row };
      this.open = true;
      this.title = "修改设备";
    },
    /** 查看按钮操作 */
    view(row) {
      // this.form = { ...row };
      getSbDetail(row.datagathercode).then((res) => {
        if (res.code === 200) {
          console.log(">>>详情啊", res);
          this.form = { ...res.data };
          if (this.form.polluteid) {
            this.getPkList(this.form.polluteid);
          }
        }
      });
      this.open = true;
      this.title = "查看设备";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let id;
      if (row) {
        id = row.datagathercode;
      } else {
        if (this.ids.length === 0) {
          this.$message.warning("请选择需要删除的设备");
          return;
        }
        id = this.ids.join(",");
      }

      this.$modal
        .confirm("是否确认删除选中的设备？")
        .then(() => {
          return delSb(id);
          // return false;
        })
        .then((res) => {
          if (res.code === 200) {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          } else {
            this.$modal.msgError("删除失败：" + (res.msg || "未知错误"));
          }
        })
        .catch((err) => {
          if (err !== "cancel") {
            this.$modal.msgError("删除操作失败");
          }
        });
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置查询表单
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        region: "",
        // attentionLevel: "全部",
        pollutename: "",
        devicename: "",
        datagathercode: "",
      };
      this.getList();
    },
    // 弹出层取消按钮
    cancel() {
      this.open = false;
      this.$refs.form.resetFields();
      // 取消时启用表单
      this.$nextTick(() => {
        const formFields = this.$refs.form.fields;
        if (formFields) {
          formFields.forEach((field) => {
            field.disabled = false;
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.datagathercode && this.title === "修改设备") {
            // 修改操作;
            updateSb(this.form)
              .then((res) => {
                if (res.code === 200) {
                  this.open = false;
                  this.$modal.msgSuccess("修改成功");
                  this.getList();
                } else {
                  this.$modal.msgError("修改失败：" + (res.msg || "未知错误"));
                }
              })
              .catch(() => {
                this.$modal.msgError("修改接口调用失败");
              });
          } else {
            // 新增操作
            addSb(this.form)
              .then((res) => {
                if (res.code === 200) {
                  this.open = false;
                  this.$modal.msgSuccess("新增成功");
                  this.getList();
                } else {
                  this.$modal.msgError("新增失败：" + (res.msg || "未知错误"));
                }
              })
              .catch(() => {
                this.$modal.msgError("新增接口调用失败");
              });
          }
        }
      });
    },

    // 获取表格数据
    getList() {
      this.ids = [];
      this.loading = true;
      getSbTableList(this.queryParams)
        .then((res) => {
          if (res.code === 200) {
            this.tableList.total = res.total;
            this.tableList.rows = res.rows;
          } else {
            this.$message.error("获取设备列表失败：" + (res.msg || "未知错误"));
            this.tableList.total = 0;
            this.tableList.rows = [];
          }
          this.loading = false;
        })
        .catch(() => {
          this.$message.error("获取设备列表接口调用失败");
          this.tableList.total = 0;
          this.tableList.rows = [];
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  // 控制分页的样式----二次开发
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  // 控制分页刷新按钮样式
  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    // .el-card__body {
    //   padding-left: 0 !important;
    // }
    .el-form-item {
      margin: 20px 0 20px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
      // & > div {
      //   width: 100% !important;
      // }
    }

    .searchBtnBox {
      display: inline-block;
      margin: 20px 0 20px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 10px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
// 左右横排的标题和更多
.titleBox {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dfe4ed;
  margin: 0 20px 20px 20px;
  position: relative;
  &::before {
    display: block;
    content: "";
    width: 3px;
    height: 16px;
    background: #307eff;
  }
  .title {
    font-size: 16px;
    color: #000;
    position: absolute;
    left: 10px;
    font-weight: 500;
  }
  .more {
    font-size: 16px;
    color: #999;
    cursor: pointer;
  }
}
</style>
